﻿using MongoDB.Driver;
using Sustainalytics.Entities.RiskRatings;
using Sustainalytics.ScreeningTool.Synchronization.Caches;
using System.Collections.Generic;
using System.Linq;

namespace Sustainalytics.ScreeningTool.Synchronization.Handlers.RiskRatings
{
    public class ComprehensiveIndicatorHandler : IHandlerWithGrouping<ComprehensiveRiskRatingIndicator>
    {
        private readonly MeiNamesCache _meiNamesCache;

        public ComprehensiveIndicatorHandler(MeiNamesCache meiNamesCache)
        {
            _meiNamesCache = meiNamesCache;
        }

        public ProjectionDefinition<ComprehensiveRiskRatingIndicator> GetProjection(ProjectionDefinitionBuilder<ComprehensiveRiskRatingIndicator> builder) => builder
            .Include(x => x.IndicatorType)
            .Include(x => x.Code)
            .Include(x => x.Name)
            .Include(x => x.MeiExternalId)
            .Include(x => x.Comment)
            .Include(x => x.AnswerCategory)
            .Include(x => x.AnswerCategoryText)
            .Include(x => x.RawScore)
            .Include(x => x.AggregatedWeight)
            .Include(x => x.AggregatedWeightedScore);

        public IEnumerable<ExtraElement> GetExtraElements(IEnumerable<ComprehensiveRiskRatingIndicator> entities)
            => entities.GroupBy(x => (x.IndicatorType, x.Code, x.Name)).SelectMany(grp =>
            {
                var key = grp.Key.GetIndicatorKey();
                var issueMapping = grp.Select(i => _meiNamesCache[i.MeiExternalId]).JoinStrings("; ");
                var x = grp.First();

                return new ExtraElementList
                {
                    { $"{key}-Issue Mapping-RR",               issueMapping              },
                    { $"{key}-Commentary-RR",                  x.Comment                 },
                    { $"{key}-Answer Category-RR",             x.GetAnswerCategory()     },
                    { $"{key}-Raw Score-RR",                   x.RawScore                },
                    { $"{key}-Weight-Consolidated-RR",         x.AggregatedWeight        },
                    { $"{key}-Weighted Score-Consolidated-RR", x.AggregatedWeightedScore },
                };
            });
    }
}
